﻿using Model.DocumentDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Studio.DocumentDB.Dialogs
{
    /// <summary>Window querying the user about a new DocDB database.</summary>
    public partial class NewDbWindow : Window
    {
        /// <summary>Account.</summary>
        /// <remarks>Input by the consumer.</remarks>
        public AccountViewModel Account { get; set; }

        /// <summary>Database.</summary>
        /// <remarks>Output.</remarks>
        public DatabaseViewModel Database { get; private set; }

        /// <summary>Constructor.</summary>
        public NewDbWindow()
        {
            InitializeComponent();

            ValidateForm();
        }

        private async void Ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var id = idBox.Text;
                var task = Account.CreateDbAsync(id);
                var waitWindow = new WaitWindow
                {
                    WaitingTask = task,
                    Owner = Window.GetWindow(this)
                };

                waitWindow.ShowDialog();

                Database = await task;
                DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    this,
                    "New DB:  " + ex.Message,
                    "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }

        private void idBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateForm();
        }

        private void ValidateForm()
        {
            okButton.IsEnabled = !string.IsNullOrWhiteSpace(idBox.Text);
        }
    }
}
